package com.phpxiu.app.push;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.msg.CustomNotice;
import com.phpxiu.app.model.msg.LiveStartNotice;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.NotificationOptionsWin;
import com.phpxiu.app.view.WelCome;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElem;
import com.tencent.TIMGroupReceiveMessageOpt;
import com.tencent.TIMMessage;
import com.tencent.TIMOfflinePushNotification;
import com.tencent.TIMTextElem;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.io.UnsupportedEncodingException;
import java.util.Observable;
import java.util.Observer;
/**
 * @file
 * @brief 推送通知处理类
 * @author 吴金洲
 * @note  推送通知处理，解析在线、离线消息，创建并展示通知，执行通知的点击跳转
 *
 */
public class PushUtil implements Observer {
    private final static Gson gson=new Gson();
    private final int pushId=1;
    private static PushUtil instance = new PushUtil();
    private PushUtil() {

    }

    public static PushUtil getInstance(){
        return instance;
    }

    private void PushNotify(TIMMessage msg){
        KKYUtil.log("收到在线通知：" + msg.getConversation().getPeer());
        if (msg==null){
            return;
        }
        //群消息和系统消息不显示通知
        if(msg.getConversation().getType()== TIMConversationType.System||msg.getConversation().getType()== TIMConversationType.Group){
            return;
        }

        if(msg.isSelf()||msg.getRecvFlag() == TIMGroupReceiveMessageOpt.ReceiveNotNotify){
            return;
        }
        //只处理文本消息和自定义消息
        TIMElem elem=msg.getElement(0);
        try {
            if(elem instanceof TIMTextElem ||elem instanceof TIMCustomElem){
                Intent win = new Intent(KKYApp.getInstance(), NotificationOptionsWin.class);
                PendingIntent intent=null;
                if(elem instanceof TIMCustomElem){
                    String customText = new String(((TIMCustomElem) elem).getData(), "UTF-8");
                    CustomNotice notice=gson.fromJson(customText,CustomNotice.class);
                    if(notice.getUserAction()!= Constants.AV_IM_CMD_LIVE_PUSH_MSG){//如果不是开播推送的其它自定义消息，不显示通知
                        return;
                    }
                    KKYUtil.log("收到自定义开播通知:"+customText);
                    LiveStartNotice notification=gson.fromJson(customText,LiveStartNotice.class);
                    win.putExtra(NotificationOptionsWin.EXTRA_ACTION_KEY,NotificationOptionsWin.ACTION_LIVE);
                    win.putExtra(NotificationOptionsWin.EXTRA_USER_ID,notification.getActionParam().getUid());
                    KKYUtil.log("开播通知主播id="+notification.getActionParam().getUid());
                    String desc=((TIMCustomElem) elem).getDesc();
                    intent= PendingIntent.getActivity(KKYApp.getInstance(), 0,
                            win, PendingIntent.FLAG_UPDATE_CURRENT);//http://my.oschina.net/u/1777508/blog/308571
                    notification(notification.getActionParam().getNickname(),desc,intent);
                }else{
                    String text=((TIMTextElem)elem).getText();
                    String nickName=msg.getSenderProfile().getNickName();
                    if(nickName==null){
                        nickName=msg.getSender();
                    }
                    //win.putExtra(Main.EXTRA_CONVERSATION_PEER,msg.getConversation().getPeer());
                    win.putExtra(NotificationOptionsWin.EXTRA_ACTION_KEY,NotificationOptionsWin.ACTION_CHAT);
                    intent= PendingIntent.getActivity(KKYApp.getInstance(), 0,
                            win, PendingIntent.FLAG_UPDATE_CURRENT);
                    notification(nickName,text,intent);
                }
            }
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JsonParseException e) {
            CrashReport.postCatchedException(e);
        }catch (NullPointerException e){
            CrashReport.postCatchedException(e);
        }
    }

    /**
     * 显示离线通知
     * @param notification
     */
    public void pushNotify(TIMOfflinePushNotification notification){
        String cid=notification.getConversationId();
        KKYUtil.log("收到离线消息："+cid);
        if(cid==null||"".equals(cid)){
            try {
                NoticeExt ext=gson.fromJson(new String(notification.getExt(),"UTF-8"),NoticeExt.class);
            }catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return;
            }catch (JsonParseException e){
                return;
            }catch (NullPointerException e){
                return;
            }
        }
        //开播消息没有会话id
        Intent win = new Intent(KKYApp.getInstance(), WelCome.class);
        PendingIntent intent= PendingIntent.getActivity(KKYApp.getInstance(), 0,
                win, 0);
        String title=notification.getTitle();
        String msg=notification.getContent();
        if(cid==null||"".equals(cid)){//开播通知
            title= KKYApp.getInstance().getString(R.string.app_name);
        }
        notification(title,msg,intent);
    }

    /**
     * 显示通知
     * @param title
     * @param msg
     */
    private void notification(String title,String msg,PendingIntent intent){
        NotificationManager mNotificationManager = (NotificationManager) KKYApp.getInstance().getSystemService(KKYApp.getInstance().NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(KKYApp.getInstance());
        mBuilder.setContentTitle(title)//设置通知栏标题
                .setContentText(msg)
                .setContentIntent(intent) //设置通知栏点击执行跳转事件
                .setTicker(msg) //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON
        Notification notify = mBuilder.build();
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(pushId, notify);
    }

    /**
     * 是否接收显示
     * @param enable
     */
    public void receivable(boolean enable){
        KKYUtil.log("通知管理对象："+(enable?"接收显示通知":"不接收显示通知"));
        if(enable){
            MessageEvent.getInstance().addObserver(this);
        }else{
            MessageEvent.getInstance().deleteObserver(this);
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        if (observable instanceof MessageEvent){
            TIMMessage msg = (TIMMessage) data;
            if (msg != null){
                PushNotify(msg);
            }
        }
    }
}
